<template>
  <div class="list-content">
    <el-row type="flex" justify="space-between">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
        <el-form-item v-if="isMuilUnitUser">
          <el-select filterable @change="getData(1)" v-model="formInline.orgIds" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgOptionsAll"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.pointTypeId" placeholder="全部类别" filterable clearable @change="getData(1)">
            <el-option v-for="item in typeOptions" :key="item.id" :label="item.pointTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="formInline.name"
            placeholder="请输入点位编码、名称、地址"
            @keyup.enter.native="getData(1)"
            clearable
            style="width:260px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getData(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns">
        <el-button v-if="!isMuilUnitUser||true" type="primary" @click="addPoint(1)">新增</el-button>
        <el-button type="primary" @click="handleExportPoint">批量生成点位图片</el-button>
        <el-button icon="el-icon-download" :loading="exporting" type="primary" @click="handleExportQrcode">批量导出二维码</el-button>
      </div>
    </el-row>
    <el-row class="overview-wrap" :gutter="40">
      <el-col :span="8">
        <div class="item-wrap">
          <p class="item-value color-8">{{ orgAmount }}</p>
          <p class="item-title">单位总数</p>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap">
          <p class="item-value color-3">{{ pointCount }}</p>
          <p class="item-title">点位总数</p>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap">
          <p class="item-value color-4">{{ Math.round(pointCount/orgAmount) }}</p>
          <p class="item-title">单位平均点位数</p>
        </div>
      </el-col>
    </el-row>
    <el-table
      v-show="pointCount>0"
      v-loading="loading"
      :data="tableData"
      ref="mainTable"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column prop="picUrl" label="安装位置照片" width="110">
        <template slot-scope="sc">
          <div v-if="sc.row.picUrl">
            <el-image
              :src="formatPicUrl(sc.row.picUrl.split(',')[0])"
              :preview-src-list="sc.row.picUrl.split(',')"
              fit="fill"
              style="width:50px;height:50px;"
            ></el-image>
          </div>
          <el-image v-else :src="defaultImg" style="width:50px;height:50px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="点位名称"></el-table-column>
      <el-table-column prop="typeName" label="所属点位类别"></el-table-column>
      <el-table-column v-if="isMuilUnitUser" prop="orgName" label="所属单位"></el-table-column>
      <el-table-column prop="buildLevelName" label="所属建筑物"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column label="二维码" prop="pointCode" width="110">
        <template slot-scope="scope">
          <div class="d-flex ai-center">
            <el-popover placement="top" width="320" trigger="hover">
              <div class="qr-hover-wrap" :id="'inspectPointQr'+scope.row.id">
                <vue-qr :text="scope.row.pointCode || ''" :size="200" :margin="10"></vue-qr>
                <p class="qr-code-text">{{ scope.row.pointCode }}</p>
              </div>
              <vue-qr
                v-if="scope.row.pointCode"
                slot="reference"
                :text="scope.row.pointCode||''"
                :size="50"
                :margin="0"
                :dotScale="0.75"
              ></vue-qr>
            </el-popover>
            <el-button @click="handleExport(scope.row)" type="text" size="small" style="margin-left:10px;">导出</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="!isMuilUnitUser||true" label="操作" width="140">
        <template slot-scope="scope">
          <el-button @click="handleOpenDialog('PointDetail', scope.row)" type="text" size="small">详情</el-button>
          <span class="dividing-line">|</span>
          <el-button @click="addPoint(scope.$index, scope.row)" type="text" size="small">编辑</el-button>
          <span class="dividing-line">|</span>
          <el-button @click="delPoint(scope.$index, scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="showEmpty&&pointCount==0" class="text-center">
      <img
        src="../../assets/images/inspect/no-point.png"
        style="margin-top:calc(50vh - 417px);width:600px;height:424px;"
      />
    </div>
    <el-pagination
      v-show="pointCount>0"
      background
      @size-change="sizeChange"
      @current-change="pageChange"
      :current-page="formInline.currentPageIndex"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pointCount"
    ></el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      :title="(editInfo.id?'编辑':'新增')+'巡检点位'"
      width="600px"
      top="10vh"
      v-if="dialogFalg"
      :visible.sync="dialogFalg"
      @close="closeDialog"
      v-dialogDrag
    >
      <edit-form :editInfo="editInfo" :pointTypeList="typeOptions" :closeDialog="closeDialog"></edit-form>
    </el-dialog>
    <point-detail ref="PointDetail" v-if="dialogVisible.PointDetail"></point-detail>
  </div>
</template>

<script>
import util from '@/utils/util'
import {
  getInspectPointTypeList,
  getInspectPointNewList,
  delInspectPointNewById,
} from '@/api/inspectx'
import editForm from './Dialog/InspectPointForm'
import PointDetail from './Dialog/PointDetail'
import { mapState, mapGetters } from 'vuex'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

export default {
  name: 'InspectPoint',
  props: ['param'],
  components: {
    editForm,
    PointDetail,
  },
  data() {
    return {
      showEmpty: false,
      dialogVisible: {
        PointDetail: false,
      },
      pointCount: 0,
      formInline: {
        name: '',
        result: '-1',
        orgIds: '',
        time: '',
        currentPageSize: 10,
        currentPageIndex: 1,
        currentPageTotal: 0,
        pointTypeId: '',
      },
      buildList: [],
      accountName: this.$store.state.userinfo.accountName,
      defaultImg: require('../../assets/images/inspect/default-point.png'),
      tableData: [], //表格数据
      detailTableData: [], //详情表格数据
      loading: false,
      dialogFalg: false,
      typeOptions: [],
      multipleSelection: [],
      exporting: false,
    }
  },
  computed: {
    ...mapState(['orgOptions']),
    ...mapGetters([
      'isMuilUnitUser',
      'userOrgId',
      'userOrgIds',
      'orgOptionsAll',
    ]),
    orgAmount() {
      return this.formInline.orgIds.toString().indexOf(',') > -1
        ? this.orgOptions.length || 1
        : 1
    },
  },
  created: function () {
    this.formInline.orgIds = this.isMuilUnitUser
      ? this.userOrgIds
      : this.userOrgId
    this.getData(1)
  },
  activated() {
    this.getInspectPointTypeList()
  },
  methods: {
    handleExport(row) {
      let dataUrl = document
        .querySelector('#inspectPointQr' + row.id + ' img')
        .getAttribute('src')
      saveAs(util.dataURLtoBlob(dataUrl), `${row.pointCode}.png`)
    },
    getInspectPointTypeList() {
      getInspectPointTypeList({
        queryType: 0,
      }).then((res) => {
        this.typeOptions = res.data
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleOpenDialog(key, data) {
      this.dialogVisible[key] = true
      this.$nextTick(() => {
        this.$refs[key].init(data)
      })
    },
    formatPicUrl: util.formatPicUrl,
    handleExportQrcode() {
      if (this.multipleSelection.length == 0) {
        return this.$message.warning('请先选择点位')
      }
      this.exporting = true
      let list = this.multipleSelection
      var srcArrL = list.length
      var zip = new JSZip()
      //压缩包文件夹名称
      var qrCodeImg = zip.folder('巡检点位二维码')
      for (var i = 0; i < srcArrL; i++) {
        let dataURL = document
          .querySelector('#inspectPointQr' + list[i].id + ' img')
          .getAttribute('src')
        var blobData = util.dataURLtoBlob(dataURL)
        qrCodeImg.file(list[i].pointCode + '.png', blobData, { base64: true })
        if (i == srcArrL - 1) {
          //循环结束保存压缩包
          //将zip序列化为二进制流
          zip
            .generateAsync({ type: 'blob' })
            .then(function (content) {
              saveAs(content, `巡检点位二维码(${srcArrL}).zip`)
              this.exporting = false
            })
            .catch((e) => {
              this.exporting = false
            })
        }
      }
    },
    //点位图片
    handleExportPoint() {
      this.$router.push({ name: 'pointPhoto' })
    },
    sizeChange(val) {
      //页码切换
      this.formInline.currentPageIndex = 1
      this.formInline.currentPageSize = val
      this.getList()
    },
    pageChange(val) {
      //翻页
      this.formInline.currentPageIndex = val
      this.getList()
    },
    getData(_pageIndex) {
      this.getList(_pageIndex)
    },
    getList(_pageIndex) {
      //获取列表
      if (_pageIndex) {
        this.formInline.currentPageIndex = _pageIndex
      }
      this.loading = true
      getInspectPointNewList({
        queryType: 1,
        pageIndex: this.formInline.currentPageIndex - 1,
        pageSize: this.formInline.currentPageSize,
        orgIds: this.formInline.orgIds,
        queryContent: this.formInline.name.trim(),
        pointTypeId: this.formInline.pointTypeId,
      }).then((result) => {
        this.pointCount = result.total
        this.tableData = result.data
        this.loading = false
        this.showEmpty = true
      })
    },
    addPoint(index, row) {
      this.dialogFalg = true
      this.editInfo = row || {}
    },
    closeDialog(refresh) {
      this.dialogFalg = false
      if (refresh) {
        this.getData(this.editInfo.id ? '' : 1)
      }
    },
    delPoint(index, row) {
      let that = this
      this.$confirm(
        '删除巡检点位，不会影响已经生成的巡检任务。是否确定删除？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true,
        }
      )
        .then(() => {
          delInspectPointNewById({ id: row.id }).then((res) => {
            if (res.status === 200) {
              if (res.data === 200011) {
                this.$message({
                  message: '该点位已被路线关联，不能删除！',
                  type: 'warning',
                })
              } else {
                that.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                that.getData(1)
              }
            } else {
              that.$message.error(res.info)
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>
<style lang="scss">
.qr-hover-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  .qr-code-text {
    margin-top: 10px;
  }
}
</style>
